#ifndef CPLATFORMPROXYXMLIMPL_H_
#define CPLATFORMPROXYXMLIMPL_H_

#include <mutex>
#include <thread>
#include <map>

#include "IPlatformProxyInterface.h"

#define TCODE_ORDER_DEPOSIT "1001"      ///< 终端上传存物信息
#define TCODE_ORDER_FETCH   "1002"      ///< 终端上传取物信息
#define TCODE_PAIDDETAILS   "1003"      ///< 终端上传支付信息
#define TCODE_STATUS        "1004"      ///< 终端上传状态信息
#define TCODE_OPEN          "1005"      ///< 终端回复开箱指令
#define TCODE_CLEAR         "1006"      ///< 终端回复清箱指令
#define TCODE_LOGS          "1007"      ///< 终端上报操作日志
#define TCODE_SYNCTIME      "1011"      ///< 终端请求同步时间(心跳请求)
#define TCODE_ORDERDETAILS  "1012"      ///< 终端查询异柜存包信息
#define TCODE_SHUTDOWN      "1013"      ///< 终端回复重启/关机指令
#define TCODE_REMOTECANCEL  "1009"      ///< 管理台远程撤销交易

class CPlatformProxyXMLImpl : public zl::IPlatformProxyInterface
{
public:
    static CPlatformProxyXMLImpl* Instance();
    static void Release();

    int32_t Initialize(const PlatConfig &conf, zl::IPlatformProxyObserver *obs) override;

    int32_t Uninitialize() override;

    int32_t ReportOrderStatus(const std::string& cabinet_no, const zl::Order& order) override;

    int32_t ReportPaidDetails(const std::string& cabinet_no, const zl::PaidDetail& data) override;

    int32_t ReportCabinetStatus(const std::string& cabinet_no, const zl::LockerVec& lockers) override;

    int32_t ReportOperationLogs(const zl::OperLog &log) override;

    int32_t RequestSynchronizeTime(const std::string& cabinet_no) override;

    int32_t RequestOrderDetails(const std::string& cabinet_no, const std::string& user_id, const std::string& user_code) override;

    int32_t ResponseOpenBox(const std::string &log_id, const std::string &cabinet_no, const std::string &box_no) override;

    int32_t ResponseClearBox(const std::string &log_id, const std::string &cabinet_no, const std::string &box_no) override;

    int32_t ResponseShutDown(const std::string &log_id, const std::string &cabinet_no, const std::string &oper_type) override;

protected:
    CPlatformProxyXMLImpl();
    ~CPlatformProxyXMLImpl();

    /// 数据接收处理线程
    static void recv_work_thread(CPlatformProxyXMLImpl* ptr);

    /// 同步发送数据
    int32_t sync_send_package(const char* buf, size_t len);

    /// 数据序列化函数
    int32_t serialize_data(const std::string& code, const std::map<std::string, std::string> &data, std::string& buf);

    /// 处理接受到的数据报文
    int32_t process_received_datagram(const std::string& content);

    /// 调用事件通知接口
    int32_t notify_all(const zl::PairParams& data);

    /// 生成logid
    std::string generate_logid();

private:
    static CPlatformProxyXMLImpl* instance_;

    std::mutex mutex_;
    std::thread* recv_thread_;
    bool recv_flag_;
    struct NetImpl;
    NetImpl* net_;
    zl::IPlatformProxyInterface::PlatConfig config_;
    zl::IPlatformProxyObserver* obs_;
};

#endif // CPLATFORMPROXYXMLIMPL_H_
